package com.example.learnnacos;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.learnnacos.clients.svb.HelloClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/hello")
@RefreshScope
public class HelloController {

//    @Autowired
//    private Config config;

//    @Value("${hello.val}")
//    private String val;

    @Autowired
    private HelloClient helloClient;

    @GetMapping("/")
    public Map<String, Object> index() {
        Map result = helloClient.callHello();
        log.info("result: {}", result);
        Map syncResult = helloClient.callSyncSay();
        log.info("syncResult: {}", syncResult);
        return Map.of("result", result, "syncResult", syncResult);
    }

    @GetMapping("/mysentinel")
    @SentinelResource(value = "hello-mysentinel", blockHandler = "handleBlock", fallback = "")
    public Map<String, Object> mysentinel() {
        log.info("/hello/mysentinel: {}", true);
        return Map.of("sc", System.currentTimeMillis(), "msg", "Hello World!");
    }

    public Map<String, Object> handleBlock(BlockException e) {
        log.info("/hello/mysentinel: {}", false);
        return Map.of("sc", System.currentTimeMillis(), "failed", e.toString());
    }

    public Map<String, Object> fallback() {
        log.info("/hello/mysentinel: {}", false);
        return Map.of("sc", System.currentTimeMillis(), "failed", System.currentTimeMillis());
    }
}
